package com.tio.demo;

import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;

/**
 * Author      : liyuemin
 * Time        : 2017/12/14 14:52
 * Description :
 */
public class HelloClientHandler implements ClientAioHandler{
    private static HelloPacket heartbeatPacket = new HelloPacket();
    public Packet heartbeatPacket() {
        return heartbeatPacket;
    }

    public Packet decode(ByteBuffer byteBuffer, ChannelContext channelContext) throws AioDecodeException {
        int realLength  = byteBuffer.limit()- byteBuffer.position();
        if(realLength<HelloPacket.HEADER_LENGTH){
            return null;
        }
        int bodyLength  = byteBuffer.getInt();
        if(bodyLength<0){
            throw new AioDecodeException("bodylength["+bodyLength+"] is not right,remote:"+ channelContext.getClientNode());
        }
        int needLength  =HelloPacket.HEADER_LENGTH + bodyLength;
        int isDataEnough  = realLength-needLength;
        if(isDataEnough<0){
            return null;//
        }else{
            HelloPacket impacket  = new HelloPacket();
            if(bodyLength > 0){
                byte[] dts = new byte[bodyLength];
                byteBuffer.get(dts);
                impacket.setBody(dts);
            }
            return impacket;
        }

    }

    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        HelloPacket helloPacket = (HelloPacket) packet;
        byte[] body = helloPacket.getBody();
        int bodylength = 0;
        if(body!=null){
            bodylength = body.length;
        }
        int alllength =  HelloPacket.HEADER_LENGTH + bodylength;
        ByteBuffer byteBuffer  = ByteBuffer.allocate(alllength);
        byteBuffer.order(groupContext.getByteOrder());

        byteBuffer.putInt(bodylength);
        if(body !=null){
            byteBuffer.put(body);
        }
        return byteBuffer;
    }

    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        HelloPacket helloPacket = (HelloPacket) packet;
        byte[] body = helloPacket.getBody();
        if(body!= null){
            String str = new String(body,HelloPacket.CHARSTER);
            System.out.println("收到消息："+ str);
        }
        return;
    }
}
